const Router = require('@koa/router');
const svgCaptcha = require('svg-captcha')
const { sign } = require('jsonwebtoken')

const router = new Router({ prefix: '/public' })

const env = require('../../env.js')
const utils = require('../../utils')

/** 验证码 */
router.get('/captcha', async (ctx) => {
  const { width = 100, height = 40 } = ctx.query
  const captcha = svgCaptcha.create({
    size: 4,
    width: +width,
    height: +height,
    fontSize: 56,
    noise: 4,
    color: true,
    background: 'transparent',
  })
  ctx.session.captcha = captcha.text
  ctx.type = 'image/svg+xml'
  ctx.body = captcha.data
})

/**
 * 每次重启获取一个 id，用户便捷录入数据
 */
router.post('/backend/login', async (ctx) => {
  const { id, captcha } = ctx.request.body
  if (id !== env.ADMIN_KEY || captcha !== ctx.session.captcha.toString().toLowerCase()) {
    ctx.body = utils.genResponse(false, null, '账号密码错误')
    return
  }

  const token = sign({ admin: id + captcha }, env.JWT.secret, { expiresIn: '3h' })
  ctx.cookies.set(env.JWT.name, token, {
    domain: env.COOKIE.domain,
    path: '/',
    maxAge: 3 * 60 * 60 * 1000,
    httpOnly: true,
    overwrite: true,
  })
  ctx.body = utils.genResponse(true)
})

module.exports = router